package com.three.common.router;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by mathua on 2017/5/30.
 */
public final class CachedRemoteRouterManager extends RemoteRouterManager {
    public static final CachedRemoteRouterManager I = new CachedRemoteRouterManager();
    private final Cache<Long, Set<RemoteRouter>> cache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .build();

    @Override
    public Set<RemoteRouter> lookupAll(long playerId) {
        Set<RemoteRouter> cached = cache.getIfPresent(playerId);
        if (cached != null) return cached;
        Set<RemoteRouter> remoteRouters = super.lookupAll(playerId);
        if (remoteRouters != null) {
            cache.put(playerId, remoteRouters);
        }
        return remoteRouters;
    }

    @Override
    public RemoteRouter lookup(long playerId, int clientType) {
        Set<RemoteRouter> cached = this.lookupAll(playerId);
        for (RemoteRouter remoteRouter : cached) {
            if (remoteRouter.getRouteValue().getClientType() == clientType) {
                return remoteRouter;
            }
        }
        return null;
    }

    /**
     * 如果推送失败，可能是缓存不一致了，可以让本地缓存失效
     * <p>
     * 失效对应的本地缓存
     *
     * @param playerId
     */
    public void invalidateLocalCache(long playerId) {
        if (playerId != 0) cache.invalidate(playerId);
    }
}